package com.jadesoft.stock.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.jadesoft.common.service.PaginationService;
import com.jadesoft.stock.entity.SysCode;

public class ProCityUtil {
	private PaginationService persistence = new PaginationService();
	Logger logger = Logger.getLogger(ProCityUtil.class);

	private List<SysCode> provinceList = new ArrayList<SysCode>();
	private List<SysCode> cityList = new ArrayList<SysCode>();
	private List<SysCode> districtList = new ArrayList<SysCode>();

	@SuppressWarnings({ "unchecked" })
	public void loadProvince() {
		String uri = "http://www.weather.com.cn/data/citydata/china.html";
		String response = this.httpRequest(uri);
		if (StringUtils.isBlank(response)) {
			logger.error(uri);
			logger.error("不能获取省份信息");
		} else {
			JSONObject obj = JSONObject.fromObject(response);
			Set<String> codes = obj.keySet();
			SysCode province = null;
			for (String code : codes) {
				province = new SysCode(code, obj.getString(code),
						Constants.SYS_CODE_CHINA,
						Constants.SYS_CODE_LEVEL_PROVINCE,
						Constants.SYS_CODE_CATEGORY_PROCITY);
				provinceList.add(province);
			}
			logger.info("省份个数: " + provinceList.size());
		}
	}

	@SuppressWarnings({ "unchecked" })
	public void loadCity() {
		for (SysCode province : provinceList) {
			String parentCode = province.getCode();
			String uri = "http://www.weather.com.cn/data/citydata/district/";
			uri += parentCode + ".html";
			String response = this.httpRequest(uri);
			if (StringUtils.isBlank(response)) {
				logger.error(uri);
				logger.error("不能获取城市信息");
			} else {
				JSONObject obj = JSONObject.fromObject(response);
				Set<String> codes = obj.keySet();
				SysCode city = null;
				for (String code : codes) {
					city = new SysCode(code, obj.getString(code), parentCode,
							Constants.SYS_CODE_LEVEL_CITY,
							Constants.SYS_CODE_CATEGORY_PROCITY);
					cityList.add(city);
				}
				logger.info("省份: " + province.getName() + " 城市个数: "
						+ cityList.size());
			}
		}
	}

	@SuppressWarnings({ "unchecked" })
	public void loadDistrict() {
		for (SysCode city : cityList) {
			String parentCode = city.getParentCode() + city.getCode();
			String uri = "http://www.weather.com.cn/data/citydata/city/";
			uri += parentCode + ".html";
			String response = this.httpRequest(uri);
			if (StringUtils.isBlank(response)) {
				logger.error(uri);
				logger.error("不能获取区县信息");
			} else {
				JSONObject obj = JSONObject.fromObject(response);
				Set<String> codes = obj.keySet();
				SysCode district = null;
				for (String code : codes) {
					district = new SysCode(code, obj.getString(code),
							parentCode, Constants.SYS_CODE_LEVEL_DISTRICT,
							Constants.SYS_CODE_CATEGORY_PROCITY);
					districtList.add(district);
				}
				logger.info("城市: " + city.getName() + "-->区县个数: "
						+ districtList.size());
			}
		}
	}

	public String httpRequest(String uri) {
		HttpClient client = StockUtil.getHttpClient();
		BufferedReader reader = null;
		GetMethod method = new GetMethod(uri);
		try {
			int returnCode = client.executeMethod(method);
			if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
				logger.error("The get method is not implemented by this URI");
				method.getResponseBodyAsString();
			} else {
				reader = new BufferedReader(new InputStreamReader(
						method.getResponseBodyAsStream(), "utf-8"));
				String readLine;
				String text = "";
				while (((readLine = reader.readLine()) != null)) {
					text += readLine;
				}
				return text;
			}
		} catch (Exception e) {
			logger.error(e);
		} finally {
			method.releaseConnection();
			if (reader != null)
				try {
					reader.close();
				} catch (Exception fe) {
					logger.error(fe);
				}
		}
		return null;
	}

	public static void main(String[] args) {
		ProCityUtil util = new ProCityUtil();
		try {
			util.createFile();
//			util.loadProcity();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public void loadProcity() {
		loadProvince();
		loadCity();
		loadDistrict();
		for (SysCode city : cityList) {
			city.setCode(city.getParentCode() + city.getCode());
		}
		for (SysCode city : districtList) {
			city.setCode(city.getParentCode() + city.getCode());
		}
		persistence.saveObjs(provinceList.toArray());
		persistence.saveObjs(cityList.toArray());
		persistence.saveObjs(districtList.toArray());
		logger.info("save success");
	}

	@SuppressWarnings("unchecked")
	public void createFile() throws IOException {
		File file = new File(
				"C:\\Documents and Settings\\Administrator\\桌面\\city-list.js");
		file.deleteOnExit();
		file.createNewFile();
		FileWriter writer = new FileWriter(file);
		// province
		writer.append("var PROVINCE = [");
		String hql = "from SysCode a where a.category = 'procity' and a.level = 1 ";
		List<SysCode> proList = persistence.query(hql);
		for (SysCode pro : proList) {
			writer.append("['" + pro.getCode() + "','" + pro.getName() + "'],");
		}
		writer.append("],");
		writer.flush();
		// city
		writer.append("CITY = [");
		hql = "from SysCode a where a.category = 'procity' and a.level = 2 ";
		proList = persistence.query(hql);
		for (SysCode pro : proList) {
			writer.append("['" + pro.getCode() + "','" + pro.getName() + "'],");
		}
		writer.append("],");
		writer.flush();
		// DISTRICT
		writer.append("DISTRICT = [");
		hql = "from SysCode a where a.category = 'procity' and a.level = 3 ";
		proList = persistence.query(hql);
		for (SysCode pro : proList) {
			writer.append("['" + pro.getCode() + "','" + pro.getName() + "'],");
		}
		writer.append("];");

		writer.flush();
		// writer.close();
		System.out.println("ok");
	}
}
